<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, nextTick, unref, ref } from 'vue'
import { FormSchema } from '@/types/form'
import { AdminData } from "@/api/auth/admin/types";
import { ElInput } from "element-plus";
import { Dialog } from '@/components/Dialog';
import SelectIp from "@/views/auth/ip/selectIp.vue";

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<AdminData>>,
    default: () => null
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const rules = reactive({
})

const { register, methods, elFormRef } = useForm({
  schema: props.formSchema
})

watch(
  () => props.currentRow,
  (currentRow) => {
    console.log(currentRow?.groupIds)
    console.log(currentRow?.ipIds)
    if (!currentRow) return
    const { setValues } = methods
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

const dialogIpIdsRef = ref<ComponentRef<typeof Dialog>>()
const ipIdSelectRef = ref<ComponentRef<typeof SelectIp>>()

const ipIdsInput = ref<ComponentRef<typeof ElInput>>()

const dialogIpIdsVisible = ref(false);

const ipIdsFocus = async () => {
  ipIdsInput.value?.blur();
  dialogIpIdsVisible.value = true;
  await nextTick();
  const dialogIpIdsObj = unref(dialogIpIdsRef);
  dialogIpIdsObj?.toggleFull();
}

const ipIdsSelected = async () => {
  const selectObj = unref(ipIdSelectRef);
  const selectedRows = await selectObj?.getSelected();
  const { setValues } = methods
  let dataIds: number[] = [];
  if (selectedRows && selectedRows?.length > 0) {
    dataIds = selectedRows.map(data => data.service_id);
  }
  setValues({
    data_service_list: dataIds,
    txt_data_service_list: dataIds.join(",")
  })
  dialogIpIdsVisible.value = false;
}

const cancel = () => {
  dialogIpIdsVisible.value = false;
}

const loading = ref(false);

defineExpose({
  elFormRef,
  getFormData: methods.getFormData
})
</script>

<template>
  <div>
    <Form :rules="rules" @register="register">
      <template #ipIds="form">
        <ElInput ref="ipIdsInput" v-model="form['ipIds']" @focus="ipIdsFocus" placeholder="请选择" />
      </template>
    </Form>
    <Dialog v-if="dialogIpIdsVisible" ref="dialogIpIdsRef" v-model="dialogIpIdsVisible" title="选择秘文端" :width="800" :max-height="550">
      <SelectIp ref="ipIdSelectRef" />

      <template #footer>
        <ElButton @click="cancel">取消</ElButton>
        <ElButton type="primary" :loading="loading" @click="ipIdsSelected">
          确定
        </ElButton>
      </template>
    </Dialog>
  </div>
</template>
